package com.gxuwz.medical.web.taglib;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.gxuwz.medical.vo.UserContext;
import com.gxuwz.medical.web.servlet.LoginServlet;



/**
 * 自定义权限标签
 * 
 * @author: amu_1115@126.com
 * @date: 2017-6-21 下午07:38:12
 * @version V1.0
 */
public abstract class PermissionTag extends SecureTag {
	
	private static final long serialVersionUID = -3246319912302951448L;
	private static final Logger LOG = LogManager.getLogger(LoginServlet.class);
	private static final String PERMISSION_NAMES_SPLIT = ",";

	private String name = null;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	protected void verifyAttributes() throws JspException {
		String permission = getName();
		if (permission == null || "".equals(permission)) {

			String msg = "The 'name' tag attribute must be set.";
			LOG.error(msg);
			throw new JspException(msg);
		} else {
			String[] perms = permission.split(PERMISSION_NAMES_SPLIT);
			if (perms == null || perms.length == 0) {
				String msg = "The 'name' tag attribute must be set. ";
				LOG.error(msg);
				throw new JspException(msg);
			}
		}
	}

	protected abstract boolean showTagBody(String p);

	/**
	 * 
	 * @param p
	 * @return
	 */
	protected boolean isPermitted(String p) {
		boolean hasPermission = false;
		UserContext userContext = getCurrentUserInfo("user");

		if (userContext != null) {

			for (String perm : p.split(PERMISSION_NAMES_SPLIT)) {
				if (userContext.getPermsSet().contains(perm.trim())) {
					hasPermission = true;
					break;
				}
			}
		}
		return hasPermission;
	}

	@Override
	public int onDoStartTag() throws JspException {
		String p = getName();

		boolean show = showTagBody(p);
		if (show) {
			return TagSupport.EVAL_BODY_INCLUDE;
		} else {
			return TagSupport.SKIP_BODY;
		}
	}

}
